/**
 * @description convert link-card elem to link
 * @author Ling
 * @date 2024-08-08
 * */

import { IDomEditor, DomEditor, t, SlateNode, SlateTransforms, SlateEditor } from '@wangeditor/editor';
import { IButtonMenu } from '@wangeditor/editor';
import { LinkCardElement, LinkElement } from '../../custom-types';
import { LINK_ICON_SVG } from '../../icon-svg';

class ConvertToLinkCard implements IButtonMenu {
  readonly title = '链接卡片';
  readonly iconSvg = LINK_ICON_SVG; // 无 icon
  readonly tag = 'button';

  private getSelectedLinkElem(editor: IDomEditor): LinkElement | null {
    const node = DomEditor.getSelectedNodeByType(editor, 'link');
    if (node == null) return null;
    return node as LinkElement;
  }

  getValue(editor: IDomEditor): string | boolean {
    return '';
  }

  isActive(editor: IDomEditor): boolean {
    // 无需 active
    return false;
  }

  isDisabled(editor: IDomEditor): boolean {
    if (editor.selection == null) return true;

    const linkElem = this.getSelectedLinkElem(editor);
    if (linkElem == null) {
      // 选区未处于 link node ，则禁用
      return true;
    }
    return false;
  }

  async exec(editor: IDomEditor, value: string | boolean) {
    if (this.isDisabled(editor)) return;

    const linkElem = this.getSelectedLinkElem(editor);

    if (linkElem == null) return;

    const { url, target, linkType, articleId } = linkElem;
    const text = SlateNode.string(linkElem);
    const linkPath = DomEditor.findPath(editor, linkElem);
    SlateTransforms.removeNodes(editor, { at: linkPath });
    SlateTransforms.splitNodes(editor, { always: true });

    const linkCard: LinkCardElement = {
      type: 'link-card',
      linkType,
      link: url,
      title: text,
      target,
      articleId,
      children: [{ text: text }],
    };
    SlateTransforms.insertNodes(editor, linkCard);
    // 焦点后移一位
    editor.move(1);
  }
}

export default ConvertToLinkCard;
